package com.cxy.contentcenter.configuration;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.ExtendBalancer;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.core.Balancer;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author: huayushu luming
 * @date: 2020-11-27 14:54
 * @desc:
 **/
@Slf4j
public class NacosSameClusterWeightedRule extends AbstractLoadBalancerRule {
    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object o) {
        try {
            //获得集群名称
            String clusterName = nacosDiscoveryProperties.getClusterName();
            BaseLoadBalancer baseLoadBalancer = (BaseLoadBalancer) this.getLoadBalancer();
            log.info("lb={}", baseLoadBalancer);
            //想要请求的微服务名称
            String name = baseLoadBalancer.getName();
            //拿到服务相关的api
            NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();

            //1.找到指定服务的所有实例 A

            List<Instance> instances = namingService.selectInstances(name, true);
            //2.过滤出相同集群下的所有实例 B
            List<Instance> sameClusterInstances = instances.stream().filter(instance -> {
                return Objects.equals(instance.getClusterName(), clusterName);
            }).collect(Collectors.toList());
            //3.如果B是空，就用A
            List<Instance> instancesToBeChosen = new ArrayList<>();
            if(CollectionUtils.isEmpty(sameClusterInstances)){
                instancesToBeChosen=instances;
                log.warn("发生了跨集群的调用，name={},clusterName={},instances={}",
                        name,
                        clusterName,
                        instances);
            }else {
                instancesToBeChosen=sameClusterInstances;
            }
            //4.基于权重的负载均衡算法，返回一个实例
            Instance instance = ExtendBalancer.getHostByRandomWeight2(instancesToBeChosen);
            log.info("选择的实例是 port={},instance={}",instance.getPort(),instance);
            return new NacosServer(instance);

        } catch (NacosException e) {
            log.error("发生异常了", e);
            return null;
        }

    }
}

class  ExTendBalancer extends Balancer{
    public static Instance getHostByRandomWeight2(List<Instance>hosts){
        return  getHostByRandomWeight(hosts);
    }
}
